package com.wanglibao.woodtrade.woodtrade.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.google.gson.Gson;
import com.wanglibao.woodtrade.woodtrade.R;
import com.wanglibao.woodtrade.woodtrade.config.NetConfig;
import com.wanglibao.woodtrade.woodtrade.entity.GetFileName;
import com.wanglibao.woodtrade.woodtrade.entity.ResponseEntity;
import com.wanglibao.woodtrade.woodtrade.entity.ResponsePictrueNameEntity;
import com.wanglibao.woodtrade.woodtrade.jsonrpc.JsonRPCAsyncTask;
import com.wanglibao.woodtrade.woodtrade.model.City;
import com.wanglibao.woodtrade.woodtrade.model.MessageSendDetailEntity;
import com.wanglibao.woodtrade.woodtrade.model.Region;
import com.wanglibao.woodtrade.woodtrade.model.User;
import com.wanglibao.woodtrade.woodtrade.model.WoodType;
import com.wanglibao.woodtrade.woodtrade.model.WoodTypeDetail;
import com.wanglibao.woodtrade.woodtrade.model.WoodTypeDetailThreePlace;
import com.wanglibao.woodtrade.woodtrade.model.impl.CityImpl;
import com.wanglibao.woodtrade.woodtrade.model.impl.RegionImpl;
import com.wanglibao.woodtrade.woodtrade.model.impl.UserImpl;
import com.wanglibao.woodtrade.woodtrade.model.impl.WoodTypeDetailImpl;
import com.wanglibao.woodtrade.woodtrade.model.impl.WoodTypeDetailThreePlaceImpl;
import com.wanglibao.woodtrade.woodtrade.model.impl.WoodTypeImpl;
import com.wanglibao.woodtrade.woodtrade.ui.activity.adapter.ItemImgvRvCommodityAdapter;
import com.wanglibao.woodtrade.woodtrade.ui.activity.user.LoginActivity;
import com.wanglibao.woodtrade.woodtrade.util.ConserveImage;
import com.wanglibao.woodtrade.woodtrade.util.GetPicPath;
import com.wanglibao.woodtrade.woodtrade.util.SPUtil;
import com.wanglibao.woodtrade.woodtrade.util.ToastUtil;
import com.wanglibao.woodtrade.woodtrade.widget.DialogTypeDialog;
import com.wanglibao.woodtrade.woodtrade.widget.SVGridView;
import com.wanglibao.woodtrade.woodtrade.widget.WheelView.OnWheelScrollListener;
import com.wanglibao.woodtrade.woodtrade.widget.WheelView.WheelView;
import com.wanglibao.woodtrade.woodtrade.widget.WheelView.adapters.ArrayWheelAdapter;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
//发布采购、出售信息页
public class ReleaseInfoActivity extends BaseActivity {

    @Bind(R.id.rl_common_title)
    RelativeLayout rlCommonTitle;
    @Bind(R.id.tv_activity_release_info_commit)
    TextView tvActivityReleaseInfoCommit;
    @Bind(R.id.edit_activity_release_demand_title)
    EditText editActivityReleaseDemandTitle;
    @Bind(R.id.tv_activity_release_demand_type)
    TextView tvActivityReleaseDemandType;
    @Bind(R.id.edit_activity_release_demand_size)
    EditText editActivityReleaseDemandSize;
    @Bind(R.id.edit_activity_release_demand_number)
    EditText editActivityReleaseDemandNumber;
    @Bind(R.id.edit_activity_release_demand_unit)
    EditText editActivityReleaseDemandUnit;
    @Bind(R.id.tv_activity_release_demand_moblie)
    TextView tvActivityReleaseDemandMoblie;
    @Bind(R.id.edit_activity_release_demand_price)
    EditText editActivityReleaseDemandPrice;
    @Bind(R.id.edit_activity_release_demand_order_number)
    EditText editActivityReleaseDemandOrderNumber;
    @Bind(R.id.tv_activity_release_demand_company_purchase)
    TextView tv_activity_release_demand_company_purchase;
    @Bind(R.id.tv_activity_release_depot)
    TextView tv_activity_release_depot;

    @Bind(R.id.ll_activity_release_info_order_number)
    LinearLayout ll_activity_release_info_order_number;
    @Bind(R.id.ll_activity_release_demand_unit)
    LinearLayout ll_activity_release_demand_unit;
    @Bind(R.id.ll_activity_release_depot)
    LinearLayout ll_activity_release_depot;

    @Bind(R.id.ll_activity_release_demand_company_purchase)
    LinearLayout ll_activity_release_demand_company_purchase;

    @Bind(R.id.ll_activity_release_info_outer)
    LinearLayout ll_activity_release_info_outer;
    @Bind(R.id.sv_activity_release_info_view)
    ScrollView sv_activity_release_info_view;

    @Bind(R.id.tv_activity_release_info_number)
    TextView tv_activity_release_info_number;

//    @Bind(R.id.ll_activity_release_place)
//    LinearLayout ll_activity_release_place;
//    @Bind(R.id.edit_activity_release_place)
//    EditText edit_activity_release_place;

    @Bind(R.id.rv_activity_release_info_img)
    SVGridView rv_activity_release_info_img;

    List<String> mUriList;
    List<String> mImageName = new ArrayList<>();
    /*对应的SVGridView的加载图片的适配器*/
    ItemImgvRvCommodityAdapter mAdapter;

    String desName = Environment.getExternalStorageDirectory() + "/wood/commodity";
    String fileName;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /*图片的名称*/
    private String IMAGE_FILE_NAME;
    /*相机的请求码*/
    private static final int CAMERA_REQUEST_CODE = 10;
    /*高清图片的文件目录*/
    String cameraPath;

    ResponsePictrueNameEntity mNameEntity = null;
    /*存放token的实体类*/
    ResponseEntity mResponseEntity = null;
    /*临时生成的token*/
    String token = null;
    ActionSheetDialog dialog;
    List<String> upLoadFileName=new ArrayList<>();
    String type = TYPE_SUPPLY;
    boolean type_new = true;
    // 采购
    public static final String TYPE_DEMAND = "0";
    // 出售
    public static final String TYPE_SUPPLY = "1";

    List<WoodType> woodTypeList = new ArrayList<>();
    List<WoodTypeDetail> woodTypeDetails = new ArrayList<>();
    List<WoodTypeDetailThreePlace> woodTypeDetailThreePlaces = new ArrayList<>();

    List<Region> regionList = new ArrayList<>();
    List<City> cityList = new ArrayList<>();
    WoodType woodType;
    WoodTypeDetail woodTypeDetail;
    WoodTypeDetailThreePlace woodTypeDetailThreePlace;
    Region depotAddressRegion = new Region();
    Region companyPurchaseRegion = new Region();
    City depotAddressCity = new City();
    City companyPurchaseCity = new City();
    int type_depot = 1;
    int type_pruchase = 2;
    User user;

    String id;
    MessageSendDetailEntity supplyDetails;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release_info);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 19) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            rl_common_title.setPadding(0, 0, 0, 0);
        }
        initView();
    }

    private void initView() {
        addViewClicklistener(tvActivityReleaseInfoCommit, tvBack, tvActivityReleaseDemandType, tv_activity_release_depot,
                tv_activity_release_demand_company_purchase);
        Intent intent = getIntent();
        type = intent.getStringExtra("type");
        id = intent.getStringExtra("id");
        type_new = TextUtils.isEmpty(id) ? true : false;

        rv_activity_release_info_img.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == (mAdapter.mPicName.size()) && mUriList.size() > 0) {
                    fileName = format.format(new Date()) + "compress" + ".jpg";
                    IMAGE_FILE_NAME = System.currentTimeMillis() + ".jpg";
                    OkHttpUtils.post().addParams("access_key", NetConfig.ACCESS_KEY)
                            .addParams("secret_key", NetConfig.SECRET_KEY)
                            .url(NetConfig.ACHIEVE_TOKEN_URL)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(okhttp3.Call call, Exception e) {
                                }

                                @Override
                                public void onResponse(String response) {
                                    mResponseEntity = new Gson().fromJson(response, ResponseEntity.class);
                                    token = mResponseEntity.getToken();
                                }
                            });
                    ActionSheetDialogNoTitle();
                }
            }
        });


        //拿到 手机号
        if (TYPE_SUPPLY.equals(type)) {
            tvTitle.setText("发布商品信息");
            ll_activity_release_demand_company_purchase.setVisibility(View.GONE);
        } else {
            tvTitle.setText("发布采购信息");
            ll_activity_release_info_order_number.setVisibility(View.GONE);
            ll_activity_release_demand_unit.setVisibility(View.GONE);
            ll_activity_release_depot.setVisibility(View.GONE);
//            ll_activity_release_place.setVisibility(View.GONE);
            tv_activity_release_info_number.setText("采购量");
        }

        initWindow();

        woodTypeList = new WoodTypeImpl(this).getAll();
        woodType = woodTypeList.get(0);
        woodTypeDetails = new WoodTypeDetailImpl(this).getWoodTypeDetailByWoodTypeId(woodType.id);
        woodTypeDetail = woodTypeDetails.get(0);
        woodTypeDetailThreePlaces = new WoodTypeDetailThreePlaceImpl(this).getWoodTypeDetailThreePlaceByWoodTypeId(woodTypeDetail.id);
        woodTypeDetailThreePlace = woodTypeDetailThreePlaces.get(0);
        tvActivityReleaseDemandType.setText(woodType.name + "-" + woodTypeDetail.name+"-"+woodTypeDetailThreePlace.name);

        RegionImpl region = new RegionImpl(this);
        regionList = region.getAll();
        if (regionList == null || regionList.size() == 0){
            JsonRPCAsyncTask jsonRPCAsyncTask1 = new JsonRPCAsyncTask(this,
                    NetConfig.SERVER + NetConfig.TYPE_COMMON, NetConfig.region, handler,
                    "jsonObject", NetConfig.TaskId.region, new Object[]{});
            jsonRPCAsyncTask1.execute(new Void[]{});
        }else{
            if (type_new){
                depotAddressRegion = regionList.get(0);
                companyPurchaseRegion = regionList.get(0);
                cityList = new CityImpl(this).getCityByRegionId(depotAddressRegion.region_id);
                if (cityList != null && cityList.size() > 0){
                    depotAddressCity = cityList.get(0);
                    companyPurchaseCity =  cityList.get(0);
                }
                tv_activity_release_depot.setText(depotAddressRegion.region_name + "-" + (depotAddressCity == null ? "" : depotAddressCity.region_name));
                tv_activity_release_demand_company_purchase.setText(depotAddressRegion.region_name + "-" + (depotAddressCity == null ? "" : depotAddressCity.region_name));
            }
        }


        if (type_new){
            mAdapter = new ItemImgvRvCommodityAdapter(this, new ArrayList<String>(),upLoadFileName);
            rv_activity_release_info_img.setAdapter(mAdapter);
            mUriList = new ArrayList<>();
            mUriList.add("");
        }else{
            JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(this, NetConfig.SERVER + NetConfig.TYPE_MESSAGE,
                    NetConfig.messageSendDetail, handler,
                    "jsonObject", NetConfig.TaskId.messageSendDetail, new Object[]{id, type});
            jsonRPCAsyncTask.execute(new Void[]{});
        }
    }


    public static final int EXTERNAL_STORAGE_REQ_CODE = 10;
    public void requestPermission() {
        //判断当前Activity是否已经获得了该权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "please give me the permission", Toast.LENGTH_SHORT).show();
            } else {
                //进行权限请求
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_REQ_CODE);
            }
        } else {
        }
    }

    private void ActionSheetDialogNoTitle() {
        final String[] stringItems = {"拍照", "选择本地相册"};
        dialog = new ActionSheetDialog(this, stringItems, null);
        dialog.isTitleShow(false).show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        requestPermission();
                        SelectPictrueFromCamera();
                        break;
                    case 1:
                        requestPermission();
                        SelectPictrueFromSdCard();
                        break;
                    default:
                        break;
                }
            }
        });
    }

    private static final int IMAGE_REQUEST_CODE = 0;
    /*
  * 选择照片 通过系统相册 从SdCard
  */
    public void SelectPictrueFromSdCard() {
        Intent intentFromGallery = new Intent();
        intentFromGallery.setType("image/*"); // 设置文件类型
        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE);
        dialog.dismiss();
    }

    /*选择照片 通过系统相机进行拍照*/
    public void SelectPictrueFromCamera() {
        dialog.dismiss();
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            try {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = new File(Environment.getExternalStorageDirectory().getPath()
                        + "/wood/commodity/");
                if (!file.exists()) file.mkdirs();
                //指定保存路径
                cameraPath = Environment.getExternalStorageDirectory().getPath()
                        + "/wood/commodity/" + format.format(new Date()) + ".jpg";
                File imageFile = new File(cameraPath);
                Uri imageFileUri = Uri.fromFile(imageFile);
                intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);
                startActivityForResult(intent, CAMERA_REQUEST_CODE);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(this, "没有找到储存目录", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(this, "没有储存卡", Toast.LENGTH_LONG).show();
        }
    }


    public void initWindow(){
        if (Build.VERSION.SDK_INT >= 19) {
            final View decorView = getWindow().getDecorView();
            decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    Rect rect = new Rect();
                    decorView.getWindowVisibleDisplayFrame(rect);
                    int screenHeight = decorView.getRootView().getHeight();
                    int height = screenHeight-rect.bottom;
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) tvActivityReleaseInfoCommit.getLayoutParams();
                    layoutParams.setMargins(0,0,0,height);
//                    tvActivityReleaseInfoCommit
                    tvActivityReleaseInfoCommit.requestLayout();
                }
            });
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        user = new UserImpl(this).getUser();
        if (user == null) {
            startActivity(new Intent(this, LoginActivity.class));
        } else {
            tvActivityReleaseDemandMoblie.setText(user.name);
        }
    }

    private void showCityDialog(final int type) {
        final DialogTypeDialog dialogTypeDialog = new DialogTypeDialog(this);
        dialogTypeDialog .setThreeWheelVisibility();
        if (regionList == null || regionList.size() == 0){
            regionList = new RegionImpl(this).getAll();
        }
        String[] regions = RegionImpl.getRegionStrings(regionList);
        dialogTypeDialog.wheel_type.setViewAdapter(new ArrayWheelAdapter<String>(this, regions));
        dialogTypeDialog.wheel_type.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {}
            @Override
            public void onScrollingFinished(WheelView wheel) {
                cityList.clear();
                String id = regionList.get(wheel.getCurrentItem()).region_id;
                cityList = new CityImpl(ReleaseInfoActivity.this).getCityByRegionId(id);
                String[] citys = CityImpl.getStrings(cityList);
                dialogTypeDialog.wheel_typeDetail.setViewAdapter(new ArrayWheelAdapter<String>(ReleaseInfoActivity.this,
                        citys));
                dialogTypeDialog.wheel_typeDetail.setCurrentItem(0);
            }
        });
        cityList.clear();
        String id = regionList.get(0).region_id;//TODO
        cityList = new CityImpl(ReleaseInfoActivity.this).getCityByRegionId(id);
        String[] citys = CityImpl.getStrings(cityList);
        dialogTypeDialog.wheel_typeDetail.setViewAdapter(new ArrayWheelAdapter<String>(ReleaseInfoActivity.this,
                citys));

        dialogTypeDialog.tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type == type_depot) {
                    depotAddressRegion = regionList.get(dialogTypeDialog.wheel_type.getCurrentItem());
                    depotAddressCity = cityList.get(dialogTypeDialog.wheel_typeDetail.getCurrentItem());
                    tv_activity_release_depot.setText(depotAddressRegion.region_name + "-" + depotAddressCity.region_name);
                } else {
                    companyPurchaseRegion = regionList.get(dialogTypeDialog.wheel_type.getCurrentItem());
                    companyPurchaseCity = cityList.get(dialogTypeDialog.wheel_typeDetail.getCurrentItem());
                    tv_activity_release_demand_company_purchase.setText(companyPurchaseRegion.region_name + "-" + companyPurchaseCity.region_name);
                }
                dialogTypeDialog.dialog.dismiss();
            }
        });
    }

    private void showTypeDialog() {
        final DialogTypeDialog dialogTypeDialog = new DialogTypeDialog(this);
        if (woodTypeList == null || woodTypeList.size() == 0){
            woodTypeList = new WoodTypeImpl(this).getAll();
        }
        String[] woodTypeStringLists = new String[woodTypeList.size()];
        for (int i = 0; i < woodTypeList.size(); i++) {
            woodTypeStringLists[i] = (woodTypeList.get(i).name);
        }
        dialogTypeDialog.wheel_type.setViewAdapter(new ArrayWheelAdapter<String>(this, woodTypeStringLists));
        dialogTypeDialog.wheel_type.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {
            }
            @Override
            public void onScrollingFinished(WheelView wheel) {
                woodTypeDetails.clear();
                String id = woodTypeList.get(dialogTypeDialog.wheel_type.getCurrentItem()).id;
                woodTypeDetails = new WoodTypeDetailImpl(ReleaseInfoActivity.this).getWoodTypeDetailByWoodTypeId(id);
                String[] woodTypeDetailArrays = WoodTypeDetailImpl.getStringArray(woodTypeDetails);
                dialogTypeDialog.wheel_typeDetail.setViewAdapter(new ArrayWheelAdapter<String>(ReleaseInfoActivity.this,
                        woodTypeDetailArrays));

                woodTypeDetailThreePlaces.clear();
                String woodTypeDetailId = woodTypeDetails.get(0).id;
                woodTypeDetailThreePlaces = new WoodTypeDetailThreePlaceImpl(ReleaseInfoActivity.this).getWoodTypeDetailThreePlaceByWoodTypeId(woodTypeDetailId);
                String[] woodTypeDetailThreePlaceArrays = WoodTypeDetailThreePlaceImpl.getStringArray(woodTypeDetailThreePlaces);
                dialogTypeDialog.wheel_typeDetailThreePlace.setViewAdapter(new ArrayWheelAdapter<String>(ReleaseInfoActivity.this,
                        woodTypeDetailThreePlaceArrays));

                if(woodTypeDetailArrays != null && woodTypeDetailArrays.length != 0){
                    dialogTypeDialog.wheel_typeDetail.setCurrentItem(0);
                }else{
                    dialogTypeDialog.wheel_typeDetail.setCurrentItem(-1);
                }
                if(woodTypeDetailThreePlaceArrays != null && woodTypeDetailThreePlaceArrays.length != 0){
                    dialogTypeDialog.wheel_typeDetailThreePlace.setCurrentItem(0);
                }else{
                    dialogTypeDialog.wheel_typeDetailThreePlace.setCurrentItem(-1);
                }
            }
        });

        woodTypeDetails.clear();
        String id = woodTypeList.get(0).id;
        woodTypeDetails = new WoodTypeDetailImpl(ReleaseInfoActivity.this).getWoodTypeDetailByWoodTypeId(id);
        String[] woodTypeDetailArrays = WoodTypeDetailImpl.getStringArray(woodTypeDetails);
        dialogTypeDialog.wheel_typeDetail.setViewAdapter(new ArrayWheelAdapter<String>(ReleaseInfoActivity.this,
                woodTypeDetailArrays));
        dialogTypeDialog.wheel_typeDetail.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {}
            @Override
            public void onScrollingFinished(WheelView wheel) {
                woodTypeDetailThreePlaces.clear();
                String woodTypeDetailId = woodTypeDetails.get(wheel.getCurrentItem()).id;
                woodTypeDetailThreePlaces = new WoodTypeDetailThreePlaceImpl(ReleaseInfoActivity.this)
                        .getWoodTypeDetailThreePlaceByWoodTypeId(woodTypeDetailId);
                String[] woodTypeDetailThreePlaceArrays = WoodTypeDetailThreePlaceImpl.getStringArray(woodTypeDetailThreePlaces);
                dialogTypeDialog.wheel_typeDetailThreePlace.setViewAdapter(new ArrayWheelAdapter<String>(ReleaseInfoActivity.this,
                        woodTypeDetailThreePlaceArrays));
                if(woodTypeDetailThreePlaceArrays != null && woodTypeDetailThreePlaceArrays.length != 0){
                    dialogTypeDialog.wheel_typeDetailThreePlace.setCurrentItem(0);
                }else{
                    dialogTypeDialog.wheel_typeDetailThreePlace.setCurrentItem(-1);
                }
            }
        });


        woodTypeDetailThreePlaces.clear();
        String woodTypeDetailId = woodTypeDetails.get(0).id;
        woodTypeDetailThreePlaces = new WoodTypeDetailThreePlaceImpl(this).getWoodTypeDetailThreePlaceByWoodTypeId(woodTypeDetailId);
        String[] woodTypeDetailThreePlaceArrays = WoodTypeDetailThreePlaceImpl.getStringArray(woodTypeDetailThreePlaces);
        dialogTypeDialog.wheel_typeDetailThreePlace.setViewAdapter(new ArrayWheelAdapter<String>(this,woodTypeDetailThreePlaceArrays));



        dialogTypeDialog.tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int oneIndex = dialogTypeDialog.wheel_type.getCurrentItem();
                int twoIndex = dialogTypeDialog.wheel_typeDetail.getCurrentItem();
                int threeIndex = dialogTypeDialog.wheel_typeDetailThreePlace.getCurrentItem();
                woodType = woodTypeList.get(oneIndex);
                if (woodTypeDetails != null && woodTypeDetails.size() > 0){
                    if (woodTypeDetailThreePlaces != null && woodTypeDetailThreePlaces.size() > 0){
                        woodTypeDetail = woodTypeDetails.get(twoIndex);
                        woodTypeDetailThreePlace = woodTypeDetailThreePlaces.get(threeIndex);
                        tvActivityReleaseDemandType.setText(woodType.name + "-" +
                                woodTypeDetail.name + "-" + woodTypeDetailThreePlace.name);
                        dialogTypeDialog.dialog.dismiss();
                    }else {
                        ToastUtil.createNormalToast(ReleaseInfoActivity.this,"资料不完整");
                    }

                }else{
                    woodTypeDetail = null;
                    tvActivityReleaseDemandType.setText(woodType.name);
                    dialogTypeDialog.dialog.dismiss();
                }

            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_activity_release_info_commit:
                if (!TextUtils.isEmpty(editActivityReleaseDemandTitle.getText().toString()) &&
                        woodType != null &&
                        !TextUtils.isEmpty(editActivityReleaseDemandSize.getText().toString()) &&
                        !TextUtils.isEmpty(editActivityReleaseDemandNumber.getText().toString()) &&
                        ((type.equals(TYPE_SUPPLY) && depotAddressCity != null && depotAddressRegion != null &&
                                !TextUtils.isEmpty(editActivityReleaseDemandUnit.getText().toString()) &&
//                                !TextUtils.isEmpty(edit_activity_release_place.getText().toString()) &&
                                !TextUtils.isEmpty(editActivityReleaseDemandOrderNumber.getText().toString())) ||
                                (type.equals(TYPE_DEMAND) && companyPurchaseCity != null && companyPurchaseRegion != null))) {
                        sentData();
                } else {
                    ToastUtil.createLongToast(this,"资料不完整");
                }
                break;
            case R.id.tv_activity_release_demand_type:
                showTypeDialog();
                break;
            case R.id.tv_activity_release_depot:
                showCityDialog(type_depot);
                break;
            case R.id.tv_activity_release_demand_company_purchase:
                showCityDialog(type_pruchase);
                break;
        }
    }

    public void sentData() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("token",user.token);
            if (woodTypeDetail == null){
                jsonObject.put("category_id",0);
                jsonObject.put("category_name","");
            }else{
                jsonObject.put("category_id",woodTypeDetail.id);
                jsonObject.put("category_name",woodTypeDetail.name);
            }
            jsonObject.put("category_one_id", woodType.id);
            jsonObject.put("category_one_name",woodType.name);
            if (woodTypeDetailThreePlace != null){
                jsonObject.put("place_id",woodTypeDetailThreePlace.id);
                jsonObject.put("place",woodTypeDetailThreePlace.name);
            }else{
                jsonObject.put("place_id",0);
            }
            jsonObject.put("title",editActivityReleaseDemandTitle.getText().toString());
            jsonObject.put("user_name",user.name);
            jsonObject.put("moblie",user.name);
            jsonObject.put("number",editActivityReleaseDemandNumber.getText().toString());
            jsonObject.put("unit",editActivityReleaseDemandUnit.getText().toString());
            jsonObject.put("type",type);
            jsonObject.put("company_address","");
            jsonObject.put("depot_province_id","");
            jsonObject.put("depot_city_id","");
            jsonObject.put("buy_address_province_id","");
            jsonObject.put("buy_address_city_id","");

            jsonObject.put("order_number","");
            jsonObject.put("size",editActivityReleaseDemandSize.getText().toString());
            StringBuffer stringBuffer = new StringBuffer();
            for (String pictrueName : mAdapter.mPicName) {
                stringBuffer.append(pictrueName).append(",");
            }
            String string = TextUtils.isEmpty(stringBuffer.toString()) ? "" : stringBuffer.toString().substring(0, stringBuffer.length() - 1);
            jsonObject.put("img_album",string);
            String price = editActivityReleaseDemandPrice.getText().toString();
            if (TextUtils.isEmpty(price) || "0".equals(price)){
                jsonObject.put("price","-100");
            }else{
                jsonObject.put("price",price);
            }
            if (TYPE_SUPPLY.equals(type)){
                jsonObject.put("depot_province_id",depotAddressRegion.region_id);
                jsonObject.put("depot_city_id",depotAddressCity.region_id);
                jsonObject.put("order_number",editActivityReleaseDemandOrderNumber.getText().toString());
            }else{
                jsonObject.put("buy_address_province_id",companyPurchaseRegion.region_id);
                jsonObject.put("buy_address_city_id",companyPurchaseCity.region_id);
            }
            if (!type_new){
                jsonObject.put("id",supplyDetails.getId());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (type_new){
            JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(this, NetConfig.SERVER + "?c=message",
                    NetConfig.supplyCommodity, handler, "jsonObject", NetConfig.TaskId.supplyCommodity,
                    new Object[]{jsonObject});
            jsonRPCAsyncTask.execute(new Void[]{});
        }else{
            JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(this, NetConfig.SERVER + "?c=message",
                    NetConfig.messageSendOperation, handler, "jsonObject", NetConfig.TaskId.messageSendOperation,
                    new Object[]{jsonObject});
            jsonRPCAsyncTask.execute(new Void[]{});
        }

    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if(msg.arg2 != 2){
                if (msg.arg1 == NetConfig.TaskId.supplyCommodity){
                    ToastUtil.createLongToast(ReleaseInfoActivity.this, "消息发布成功");
                    setResult(RESULT_OK);
                    SPUtil.put(ReleaseInfoActivity.this,"ReleaseType",type);
                    ReleaseInfoActivity.this.finish();
                }else if (msg.arg1 == NetConfig.TaskId.region){
                    RegionImpl.analyCity(ReleaseInfoActivity.this,msg.obj.toString());
                    regionList = new RegionImpl(ReleaseInfoActivity.this).getAll();
                    if (type_new){
                        depotAddressRegion = regionList.get(0);
                        companyPurchaseRegion = regionList.get(0);
                        cityList = new CityImpl(ReleaseInfoActivity.this).getCityByRegionId(depotAddressRegion.region_id);
                        if (cityList != null && cityList.size() > 0){
                            depotAddressCity = cityList.get(0);
                            companyPurchaseCity =  cityList.get(0);
                        }
                        tv_activity_release_depot.setText(depotAddressRegion.region_name + "-" + (depotAddressCity == null ? "" : depotAddressCity.region_name));
                        tv_activity_release_demand_company_purchase.setText(depotAddressRegion.region_name + "-" + (depotAddressCity == null ? "" : depotAddressCity.region_name));
                    }
                }else if (msg.arg1 == NetConfig.TaskId.messageSendDetail){
                    Gson gson = new Gson();
                    supplyDetails = gson.fromJson(msg.obj.toString(),MessageSendDetailEntity.class);
                    woodTypeDetail.id = supplyDetails.getCategory_id();
                    woodTypeDetail.name = supplyDetails.getCategory_name();
                    woodType.id = supplyDetails.getCategory_one_id();
                    woodType.name = supplyDetails.getCategory_one_name();
                    woodTypeDetailThreePlace.id = supplyDetails.getPlace_id();
                    woodTypeDetailThreePlace.name = supplyDetails.getPlace();

                    editActivityReleaseDemandTitle.setText(supplyDetails.getTitle());
                    if (TextUtils.isEmpty(supplyDetails.getCategory_name())){
                        tvActivityReleaseDemandType.setText(supplyDetails.getCategory_one_name());
                    }else{
                        tvActivityReleaseDemandType.setText(supplyDetails.getCategory_one_name()+"-"+
                                supplyDetails.getCategory_name()+"-"+supplyDetails.getPlace());
                    }
                    editActivityReleaseDemandNumber.setText(supplyDetails.getNumber());
                    editActivityReleaseDemandUnit.setText(supplyDetails.getUnit());
//                    edit_activity_release_place.setText(supplyDetails.getPlace());
                    editActivityReleaseDemandSize.setText(supplyDetails.getSize());
                    String price = supplyDetails.getWant_price();
                    editActivityReleaseDemandPrice.setText("面议".equals(price) ? "" : price);

                    depotAddressRegion.region_id = supplyDetails.getDepot_province_id();
                    depotAddressRegion.region_name = supplyDetails.getDepot_province_name();
                    companyPurchaseRegion.region_id = supplyDetails.getBuy_address_province_id();
                    companyPurchaseRegion.region_name = supplyDetails.getBuy_address_province_name();
                    depotAddressCity.region_id = supplyDetails.getDepot_city_id();
                    depotAddressCity.region_name = supplyDetails.getDepot_city_name();
                    companyPurchaseCity.region_id = supplyDetails.getBuy_address_city_id();
                    companyPurchaseCity.region_name = supplyDetails.getBuy_address_city_name();
                    editActivityReleaseDemandOrderNumber.setText(supplyDetails.getOrder_number());
                    tv_activity_release_demand_company_purchase.setText(companyPurchaseRegion.region_name+"-"+companyPurchaseCity.region_name);
                    tv_activity_release_depot.setText(depotAddressRegion.region_name+"-"+depotAddressCity.region_name);

                    mUriList = supplyDetails.getImg_ablum_list();
                    if (mUriList.size() != 0) {
                        for (String picpictrueUrl : mUriList) {
                            upLoadFileName.add(SubString(picpictrueUrl));
                        }
                    }
                    mAdapter = new ItemImgvRvCommodityAdapter(ReleaseInfoActivity.this, mUriList, upLoadFileName);
                    rv_activity_release_info_img.setAdapter(mAdapter);
                }else if(msg.arg1 == NetConfig.TaskId.messageSendOperation){
                    ToastUtil.createLongToast(ReleaseInfoActivity.this, "消息修改成功");
                    ReleaseInfoActivity.this.finish();
                }

            }
            return false;
        }
    });
    public String SubString(String pictrueUrl) {
        String string = pictrueUrl;
        int i = string.indexOf("file=");
        int i1 = string.lastIndexOf("&");
        String s = string.substring(i + 5, i1);
        return s;
    }

    /*拍照完成后返回，对图片进行压缩比例，上传图片，并且展示*/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        } else {
            if (requestCode == CAMERA_REQUEST_CODE) {
                File file1 = ConserveImage.compressImage(cameraPath, desName, fileName, Bitmap.CompressFormat.JPEG, 100);
                uri1 = Uri.fromFile(file1);
                take = 0;
                upLoadPictrue(file1);

            }
            if (requestCode == IMAGE_REQUEST_CODE) {
                Uri uri = data.getData();
                String string = uri.getPath();
                String path;
                if (android.os.Build.VERSION_CODES.KITKAT >= 19) {  // 或者 android.os.Build.VERSION_CODES.KITKAT这个常量的值是19
                    path = new GetPicPath().getPath_above19(this, uri);
                    System.out.println("path_above19:" + path);
                } else {
                    path = getFilePath_below19(uri);

                }
                File file2 = ConserveImage.compressImage(path, desName, fileName, Bitmap.CompressFormat.JPEG, 100);
                uri2 = Uri.fromFile(file2);
                take = 1;
                upLoadPictrue(file2);

            }
        }
    }

    /**
     * API19以下获取图片路径的方法
     *
     * @param uri
     */
    private String getFilePath_below19(Uri uri) {
        //这里开始的第二部分，获取图片的路径：低版本的是没问题的，但是sdk>19会获取不到
        String[] proj = {MediaStore.Images.Media.DATA};
        //好像是android多媒体数据库的封装接口，具体的看Android文档
        Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
        //获得用户选择的图片的索引值
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        System.out.println("***************" + column_index);
        //将光标移至开头 ，这个很重要，不小心很容易引起越界
        cursor.moveToFirst();
        //最后根据索引值获取图片路径   结果类似：/mnt/sdcard/DCIM/Camera/IMG_20151124_013332.jpg
        String path = cursor.getString(column_index);
        System.out.println("path:" + path);
        return path;
    }

    String PicName = null;
    int take;
    Uri uri1;
    Uri uri2;
    /**
     * @param file 上传的图片
     */
    public void upLoadPictrue(final File file) {
        if (token != null) {
            OkHttpUtils.post()
                    .addParams("token", token)
                    .addFile("filename", IMAGE_FILE_NAME, file)
                    .url(NetConfig.PICTRUE_UPLOAD_URL)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(okhttp3.Call call, Exception e) {
                        }

                        @Override
                        public void onResponse(String response) {
                            mNameEntity = new Gson().fromJson(response, ResponsePictrueNameEntity.class);
                            GetFileName getFileName1=new Gson().fromJson(mNameEntity.getErr_msg(),GetFileName.class);
                            PicName=getFileName1.getFilename().getName();
                            mAdapter.addDataTomPicName(0,PicName);
                            if(take==0){
                                mAdapter.addData(0, String.valueOf(uri1));
                            } else {
                                mAdapter.addData(0, String.valueOf(uri2));
                            }

                        }
                    });
        }
    }


}
